<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AdoptedStyleSheets</title>
  </head>
  <body>
    <hello-css-sheet></hello-css-sheet>
    <hello-world></hello-world>
    <script>
      function getSharedStyles(webComponentStyles) {
        let adoptedStyleSheet = null;
        let styleSheet = null;
        if (window.CSSStyleSheet) {
          try {
            // 创建一个空的“构造的”样式表
            adoptedStyleSheet = new CSSStyleSheet();
            // 应用一条规则到样式表
            adoptedStyleSheet.replaceSync(webComponentStyles);
            return { adoptedStyleSheet };
          } catch (e) {
            console.warn("构造式样式表不受支持", e);
          }
        }

        // 降级方案：创建常规样式元素
        if (!styleSheet) {
          styleSheet = document.createElement("style");
          styleSheet.id = "wisequiz-shared-styles";
          styleSheet.textContent = webComponentStyles;
        }

        return { styleElement: styleSheet };
      }
      class HelloCssSheet extends HTMLElement {
        constructor() {
          super();
          this.attachShadow({ mode: "open" });

          // 优先使用 adoptedStyleSheets API
          const { adoptedStyleSheet, styleElement } = getSharedStyles(
            "h1 {  color: blueviolet; }"
          );
          // 将新规则添加到样式表中
          adoptedStyleSheet.insertRule("h1 { background-color: #999; }");
          // 在影子 DOM 中采用样式表
          if (adoptedStyleSheet && this.shadowRoot.adoptedStyleSheets) {
            this.shadowRoot.adoptedStyleSheets = [adoptedStyleSheet];
          } else if (styleElement) {
            // 降级方案：克隆样式节点
            this.shadowRoot.appendChild(styleElement.cloneNode(true));
          }

          const container = document.createElement("h1");
          container.innerHTML = "Hello CSSSheet";
          this.shadowRoot.appendChild(container);
        }
      }
      customElements.define("hello-css-sheet", HelloCssSheet);

      class HelloWorld extends HTMLElement {
        constructor() {
          super();
          const shadowDOM = this.attachShadow({ mode: "open" });
          const container = document.createElement("h1");
          container.innerHTML = "Hello World";
          shadowDOM.appendChild(container);
        }
      }
      customElements.define("hello-world", HelloWorld);
    </script>
  </body>
</html>
